<?php
namespace app\index\controller;

use app\admin\model\Members;
use app\admin\model\ReserveSetInfo;
use think\Controller;
use app\admin\model\FrontUser;
use app\admin\model\Product;
use think\db;
use think\Request;
use think\Session;
use app\admin\model\Reserve;

/**
 * 乐8小城预约模块
 */

class Index extends Common
{
    private $Reserve;   //当前控制器关联模型
    private $userId;   //用户ID
    private $Members;   //用户ID
    private $ReserveSetInfo;   //用户ID

    public function _initialize(){
        parent::_initialize();
        //define('MODULE_NAME', request()->module());
        $this->Reserve = new Reserve;
        $this->Members = new Members();
        $this->ReserveSetInfo = new ReserveSetInfo();
        $this->userId = Session::get('userId');
        //$this->userId = 16;//测试用户ID
    }

    //个人中心主页
    public function home(){

        $id = $this->userId;//测试ID
        $fu = new FrontUser();
        $userData = $fu->where('id',$id)->find();
        //主页菜单按钮
        $menu_link = DB::table('tf_setting')->where('reserve','menu_link')->field('num')->find();
        $this->assign('userData', $userData);
        $this->assign('menu_link', json_decode($menu_link['num'],true));
        return $this->fetch();

    }

    //
    public function index()
    {

        if (request()->isPost()){

            $data = Input('post.');
            //搜索会员卡是否存在
            $cardData = $this->Members->where('membercard',$data['membercard'])->find();
            if(empty($cardData)){
                return ajaxReturn('请填写准确的会员卡');
            }
            //正确的手机号
            if(!preg_match("/^1[34578]\d{9}$/", $data['mobile'])){
                return ajaxReturn('手机格式有误');
            }
            //账号是否禁用
            $fu = new FrontUser();
            $user_res = $fu->where('id',$this->userId)->where('status',2)->find();
            if($user_res){
                return ajaxReturn('预定失败，账号已冻结');
            }
            //判断是否够人数
            $si = $this->ReserveSetInfo->where('reserve_date',$data['reserve_date'])->where('field',$data['reserve_field'])->find();
            $nt = $data['kid'];
            if($si['num']<$nt){
                return ajaxReturn('预约人数大于剩余人数');
            }
            //判断会员卡的预约次数 #marke
            $count_c = $this->Reserve->whereIn('usage',[1,2,3])->where('membercard',$data['membercard'])->count();
            //搜索预约设置次数
            $rese_num = DB::table('tf_setting')->where('reserve','reserve')->find();
            if($count_c >=$rese_num['num']){
                return ajaxReturn('已约满，会员卡最大预约'.$rese_num['num'].'次');
            }
            //判断成人 小孩预约人数限制
            $adult = DB::table('tf_setting')->where('reserve','adult')->find();
            $kid = DB::table('tf_setting')->where('reserve','kid')->find();
            if($adult['num'] < $data['adult']){
                return ajaxReturn('大人单次预约不超过'.$adult['num'].'人');
            }
            if($kid['num'] < $data['kid']){
                return ajaxReturn('小孩单次预约不超过'.$kid['num'].'人');
            }


            //保存预约信息
            $arr = [
                'fu_id'=>$this->userId,
                'reserve_date'=>$data['reserve_date'],
                'reserve_field'=>$data['reserve_field'],
                'mobile'=>$data['mobile'],
                'adult'=>$data['adult'],
                'kid'=>$data['kid'],
                'people_num'=>$data['adult']+$data['kid'],
                'name'=>$data['name'],
                'membercard'=>$data['membercard'],
                'create_time'=>time()
            ];
            $res = $this->Reserve->insert($arr);
            $lastId = $this->Reserve->getLastInsID();
            if($res){
                //预定成功 减去剩余人数
                $this->ReserveSetInfo->where('reserve_date',$data['reserve_date'])->where('field',$data['reserve_field'])->setDec('num',$data['kid']);
            }
            if($res){
                return ajaxReturn(['status'=>'OK','id'=>$lastId]);
            }

        }else{
            //搜索可预约的日期
            $now_date = date('Y-m-d');
            $date_30 = date('Y-m-d',strtotime('+30 day'));
            $res_data = $this->ReserveSetInfo->where('reserve_date','between time',[$now_date,$date_30])->group('reserve_date')->select();
            //搜索预约页面说明
            $reserve_info = DB::table('tf_setting')->where('reserve','reserve_info')->find();
            $this->assign('data', $res_data);
            $this->assign('reserve_info', $reserve_info['num']);
            return $this->fetch();
        }
    }

    //可用场地
    public function usabledi(Request $request){

        $post_data = $request->param();
        //搜索当天日期的场次
        $res = $this->ReserveSetInfo->where('reserve_date',$post_data['date'])->where('using',1)->select();
        if(!$res){
            $res = 'nodata';
        }
        return ajaxReturn($res);
    }


    //可用场次
    public function usableci(){
        $date = Input('get.reserve_date');
        $changdi = Input('get.changdi');
        $info = [];
        if(!empty($date) && !empty($changdi)){
            //先搜索日期 是否有人定场
            $reserve_data = $this->Reserve->where('reserve_date',$date)->where('usage',0)->select();
            if(!empty($reserve_data)){
                //已定场地合集
                $hj = [];
                //有人订场
                foreach ($reserve_data as $key=>$val){
                    $rd = json_decode($val['reserve_field'],true);
                    foreach ($rd as $k => $v){
                        if($k == $changdi){
                            //场号合集
                            $hj[$changdi][$v] = $v;
                        }
                    }
                }
                //判断是否还有空余场次
                $changciArr = [];
                foreach ($hj as $key=>$val){
                    if(in_array("3",$val)){
                        break;
                    }
                    if(in_array("2",$val) && in_array("1",$val)){
                        break;
                    }
                    if(!in_array("1",$val) && !in_array("2",$val)){
                        array_push($changciArr,3);
                    }
                    if(!in_array("1",$val)){
                        array_push($changciArr,1);
                    }
                    if(!in_array("2",$val)){
                        array_push($changciArr,2);
                    }
                }
                if(empty($hj)){
                    $info['changci'] = $this->changci([3,1,2]);
                }else{
                    $info['changci'] = $this->changci($changciArr);
                }
            }else{
                $info['changci'] = $this->changci([3,1,2]);
            }
        }
        return ajaxReturn($info);
    }




    //预约余额表
    public function userList(Request $request){

        $id = $this->userId;  //测试ID
        //搜索用户头像
        $fu = new FrontUser();
        $userData = $fu->where('id',$id)->field('user_img')->find();
        $this->assign('userImg', $userData['user_img']);

        $keyword = $request->param('keyword');
        if($keyword){
            $where['name|moblie'] = ['like', '%'.$keyword.'%'];
        }
        $where['fu_id']=$id;
        if (request()->isPost()){
            //分页
            $start = Input('post.start');
            $start = isset($start) ? $start : 0;
            $dataList = $this->Reserve->where($where)->limit($start,10)->order('id','desc')->select();
            if(empty($dataList)){$dataList='nodata';}
            return ajaxReturn($dataList);
        }else{
            $dataList = $this->Reserve->where($where)->limit(0,10)->order('id','desc')->select();
            $this->assign('dataList', $dataList);
            $this->assign('total', count($dataList));
            return $this->fetch();
        }
    }

    //用户详情
    public function userInfo($id){
        //限制链接任意使用ID
        //判断用户是否


        $userData = $this->FrontUser->where('id',$id)->find();
        if(!empty($userData)){
            //搜索意向产品
            $pro_id = explode(',',$userData['product_id']);
            $where = [ 'id' => ['in', $pro_id] ];
            $pro_data = $this->Product->where($where)->select();
            $this->assign('pro_data', $pro_data);
        }
        $this->assign('userData', $userData);
        $this->assign('test','123');
        return $this->fetch();

    }

    //个人信息详情
    public function info(Request $request){
        $id = $request->param('id');
        $userid = $this->userId;
        $resdata = $this->Reserve->where('id',$id)->find();
        //搜索预约页面说明
        $explain_info = DB::table('tf_setting')->where('reserve','explain_info')->find();
        $this->assign('explain_info', $explain_info['num']);
        //计算十分钟的时间差
        $miao = 600;
        $now_time = time();
        $d = $now_time - strtotime($resdata['create_time']);
        if( $d < $miao && $resdata['usage'] != 6){
            //如果剩余秒数小于十分钟
            //可以显示取消按钮 并且将剩余秒数传给前端
            $residue = $miao - $d;
            $this->assign('residue', $residue);
        }else{
            $this->assign('residue', 'none');
        }
        $this->assign('data', $resdata);
        return $this->fetch('reserveinfo');
    }

    //用户点击取消预约
    public function cancelre(Request $request){
        $id = $request->param('id');
        //更新状态
        $this->Reserve->where('id',$id)->update(['usage'=>6]);
        //恢复人数
        $res = $this->Reserve->where('id',$id)->find();
        DB::table('tf_reserve_set_info')->where('reserve_date',$res['reserve_date'])->where('field',$res['reserve_field'])->setInc('num',$res['kid']);
        return ajaxReturn('OK');
    }

    //表单页面
    public function form(){


        if (request()->isPost()){


        }else{
            //搜索当前用户最近提交的一条信息
            $data = $this->Reserve->where('fu_id',$this->userId)->order('id desc')->find();
            $this->assign('data', $data);
            return $this->fetch();
        }
    }


}
